import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, StyleSheet, ActivityIndicator,TouchableOpacity } from 'react-native';
import {getTestList} from '../../../api/backend';
import {primaryBackgroundColor, primaryColor2,secondaryColor} from '../../../theme/default';
export function NotificationView({navigation}: any) {
  // 状态管理
  const [data, setData] = useState([]); // 存储接口返回的数据
  const [loading, setLoading] = useState(false); // 加载状态
  const [error, setError] = useState(null); // 错误状态
  const [page, setPage] = useState(1);
  const [itemsPerPage, setitemsPerPage] = useState(20);
  const [hasMore, setHasMore] = useState(true);
  // 获取数据的函数
  const fetchData = async () => {
    if (loading || !hasMore) return;
    setLoading(true);
    try {
      const response = await getTestList(page,itemsPerPage);
      setPage(page => page + 1);
      console.log(response);
      // 更新数据状态
      setData(response);
      setLoading(false);
    } catch (err) {
      setLoading(false);
    }
  };

  const fetchMoreData = async () => {
    // 如果正在加载或没有更多数据，直接返回
    if (loading || !hasMore) return;

    setLoading(true);
    try {
      console.log(page);
      const response = await getTestList(page,itemsPerPage);
      setData(prevData => [...prevData, ...response]);
      setPage(page => page + 1);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchData();
  }, []);

  // 渲染列表项
  const renderItem = ({ item }) => (
    <View style={styles.itemContainer}>
      <TouchableOpacity style={styles.button} onPress={() => navigation.navigate('NotificationDetail',{id: item.id,})}>
          <Text style={styles.itemText}>{item.name}</Text>
        </TouchableOpacity>
    </View>
  );

  return (
    <View style={styles.container}>
      <FlatList
        data={data}
        renderItem={renderItem}
        keyExtractor={(item) => item.id.toString()}
        onEndReached={fetchMoreData}
        onEndReachedThreshold={0.1}
        ListFooterComponent={loading ? <ActivityIndicator /> : null}
      />
    </View>
  );
}

// 样式
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: primaryBackgroundColor,
  },
  itemContainer: {
    height: 50,
    borderBottomWidth: 1,
    borderBottomColor: '#E0E0E0',
    
  },
  button: {
    width: '100%',
    height: 50,
    flex: 1,
    justifyContent: 'center',
  },
  itemText: {
    fontSize: 16,
    fontWeight: 'bold',
    color:'#fff',
    
  },
});
